/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package spendreport.java.examples;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.walkthrough.common.entity.Alert;
import org.apache.flink.walkthrough.common.entity.Transaction;

/**
 * Skeleton code for implementing a fraud detector.
 * @author huanghaifeng15
 */
public class FraudDetector extends KeyedProcessFunction<Long, Transaction, Alert> {

	private static final long serialVersionUID = 1L;


	/**
	 * 是否用一笔小额交易进行嗅探
	 */
	private static final double SMALL_AMOUNT = 1.00;
	/**
	 * 小额交易嗅探成功后，紧接着进行大额交易，认定为欺诈交易
	 */
	private static final double LARGE_AMOUNT = 500.00;
	/**
	 * 这对诈骗交易俩笔交易时间相近，增加的条件。时间短，可以减少被受害者发现的概率。
	 */
	private static final long ONE_MINUTE = 60 * 1000;

	/**
	 * 定义一个表示是否刚处理过一个小额交易。 当处理到该账户的一个大额交易时，你只需要检查这个标记状态来确认上一个交易是是否小额交易即可。
	 * 		类似于 Java 标准库里边的 AtomicReference 和 AtomicLong
	 */
	private transient ValueState<Boolean> flagState;

	/**
	 * 定义一个时间状态
	 */
	private transient ValueState<Long> timeState;

	/**
	 * 状态需要通过 open() 来进行注册
	 */
	@Override
	public void open(Configuration parameters) throws Exception {
		ValueStateDescriptor<Boolean> flagDescription = new ValueStateDescriptor<>("flag", Types.BOOLEAN);
		flagState = getRuntimeContext().getState(flagDescription);

		ValueStateDescriptor<Long> timeDescription = new ValueStateDescriptor<Long>("time-state",Types.LONG);
		timeState = getRuntimeContext().getState(timeDescription);
	}

	/**
	 * 该方法会在每一个交易事件上被调用。
	 * 		对每一笔交易进行报警
	 */
	@Override
	public void processElement(
			Transaction transaction,
			Context context,
			Collector<Alert> collector) throws Exception {
		// 针对当前 key 获取当前的状态
		Boolean lastTransactionWasSmall = flagState.value();

		// 校验标记是否被设置
		if (lastTransactionWasSmall != null){
			if (transaction.getAmount() > LARGE_AMOUNT){
				// 报警
				Alert alert = new Alert();
				alert.setId(transaction.getAccountId());

				collector.collect(alert);
			}

			// 清除设置的状态 flagState.clear()
			cleanUp(context);
		}

		if (transaction.getAmount() < SMALL_AMOUNT){
			// 设置标记为 true
			flagState.update(true);

			// 设置时间事件，并且设置时间状态
			long timer = context.timerService().currentProcessingTime() + ONE_MINUTE;
			context.timerService().registerProcessingTimeTimer(timer);
			timeState.update(timer);
		}
	}

	/**
	 * 当定时器触发时，会调用下面的方法
	 */
	@Override
	public void onTimer(long timestamp, OnTimerContext ctx, Collector<Alert> out) throws Exception {
		// 一分钟后清除标记
		timeState.clear();
		flagState.clear();
	}

	/**
	 * 如果要取消定时器，你需要删除已经注册的定时器，并同时清空保存定时器的状态。 你可以把这些逻辑封装到一个助手函数中，而不是直接调用 flagState.clear()
	 */
	private void cleanUp(Context ctx) throws Exception {
		// delete timer
		Long timer = timeState.value();
		ctx.timerService().deleteProcessingTimeTimer(timer);

		// clean up all state
		timeState.clear();
		flagState.clear();
	}
}
